<?php

namespace app\models;

use Yii;
use app\models\Customer;

/**
 * This is the model class for table "customer_history".
 *
 * @property int $id
 * @property int $good_id 商品id
 * @property int $customer_id 用户id
 * @property int $created_at
 */
class CustomerHistory extends Base
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'customer_history';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['good_id', 'customer_id', 'created_at'], 'integer'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'good_id' => 'Good ID',
            'customer_id' => 'Customer ID',
            'created_at' => 'Created At',
        ];
    }

    public function getCustomer(){
        return $this->hasOne(Customer::class, ['id' => 'customer_id']);
    }

    public function getGood(){
        return $this->hasOne(Good::class, ['id' => 'good_id']);
    }

    public static function saveRecord($good_id, $openid) {
        $customer = Customer::find()->where(['openid' => $openid])->one();
        if ($customer) {
            $customer_history = Self::find()->where(['customer_id' => $customer->id, 'good_id' => $good_id])->one();
            if (!$customer_history) {
                $customer_history = new CustomerHistory();
                $customer_history->customer_id = $customer->id;
                $customer_history->good_id = $good_id;
            }
            $customer_history->created_at = time();
            $customer_history->save();
        }
    }
}
